package com.fms.kccc.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fms.kccc.object.ImageContent;
import com.fms.kccc.service.ImageContentService;
import com.fms.kccc.service.ImageContentServiceImpl;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.blobstore.UploadOptions;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;

public class ImageContentServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String ACTION_ADD = "add";
	private static final String ACTION_EDIT = "edit";
	private static final String PARAMETER_ACTION = "oper";
	private static final String PARAMETER_ID = "id";
	private static final String PARAMETER_TITLE = "title";
	private static final String PARAMETER_SOURCE = "source";
	private static final String PARAMETER_IMAGEURL = "imageURL";
	private static final String PARAMETER_SMALLIMAGEURL = "smallImageURL";
	private static final String PARAMETER_CATEGORY = "category";
	private static final String PARAMETER_PAGE = "page";
	private static final String PARAMETER_ROWS = "rows";
	private boolean isUseSmallImageBakup = false;
	
	ImageContentService imageContentService = new ImageContentServiceImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		int page = Integer.parseInt(getParameter(req, PARAMETER_PAGE));
		int rows = Integer.parseInt(getParameter(req, PARAMETER_ROWS));
		String category = getParameter(req, PARAMETER_CATEGORY);
		List<ImageContent> imageContents = imageContentService
				.getImageContents(category, page, rows);
		jsonRespone(resp, HttpServletResponse.SC_OK,
				ImageContent.toJsonArray(imageContents));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = getParameter(req, PARAMETER_ACTION);
		if (action.equals(ACTION_ADD)) {
			doAdd(req, resp);
		} else if (action.equals(ACTION_EDIT)) {
			doEdit(req, resp);
		}
	}

	private void doEdit(HttpServletRequest req, HttpServletResponse resp) {
		// TODO Auto-generated method stub

	}

	private void doAdd(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String title = getParameter(req, PARAMETER_TITLE);
		String source = getParameter(req, PARAMETER_SOURCE);
		String imageURL = getParameter(req, PARAMETER_IMAGEURL);
		String smallImageURL = getParameter(req, PARAMETER_SMALLIMAGEURL);
		String category = getParameter(req, PARAMETER_CATEGORY);
		String imageURLBackup = getURLBackup(imageURL);
		String smallImageURLBackup;
		if(isUseSmallImageBakup){
			smallImageURLBackup = getURLBackup(smallImageURL);
		}else{
			smallImageURLBackup = imageURLBackup;
		}
		ImageContent imageContent = new ImageContent(title, source, imageURL,
				smallImageURL, imageURLBackup, smallImageURLBackup, category);
		imageContentService.addNewImageContent(imageContent);
	}

	public String getURLBackup(String imageURL) throws IOException {
		Blob blob = getBlobFromURL(imageURL);
		return toBlobstore(blob).getKeyString();
	}

	public Blob getBlobFromURL(String imageUrl) throws IOException {
		URL url = new URL(imageUrl);
		InputStream stream = url.openStream();
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		long streamLength = stream.available();
		byte[] data = new byte[(int) streamLength];
		int nRead;
		while ((nRead = stream.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}
		buffer.flush();
		stream.close();
		return new Blob(buffer.toByteArray());
	}

	public BlobKey toBlobstore(Blob imageData) throws IOException {
		if (null == imageData)
			return null;

		// Get a file service
		FileService fileService = FileServiceFactory.getFileService();

		// Create a new Blob file with mime-type "image/png"
		AppEngineFile file = fileService.createNewBlobFile("image/jpeg");// png

		// Open a channel to write to it
		boolean lock = true;
		FileWriteChannel writeChannel = fileService
				.openWriteChannel(file, lock);

		// This time we write to the channel directly
		writeChannel.write(ByteBuffer.wrap(imageData.getBytes()));

		// Now finalize
		writeChannel.closeFinally();
		return fileService.getBlobKey(file);
	}
}
